package nl.unimaas.games.tron.player;

import java.awt.Color;
import java.util.ArrayList;
import nl.unimaas.games.tron.engine.Board;

@SuppressWarnings("serial")
public class FillPlayer extends Player {
	private int turns = 0;
	private final ArrayList<int[]> wallCounts = new ArrayList<int[]>(4);
	private final ArrayList<int[]> newList = new ArrayList<int[]>(4);
	
	public FillPlayer(String name, int num, Color c) {
		super(name, num, c);
	}

	@Override
	protected int computeMove(Board b, long endTime) {
		turns++;
		int pos = b.getPlayerPosition(this);
		int x = Board.posToX(b, pos), y = Board.posToY(b, pos);
		ArrayList<int[]> positions = b.getValidMovePositionsXY(x, y);
		ArrayList<Integer> moves = b.getValidMoves(x, y);
		if (positions.isEmpty()) {
			return Board.MOVE_NONE;
		}
		else {
			wallCounts.clear();
			int[] p;
//			boolean hasIsoMove = false;
			for (int i = 0; i < positions.size(); i++) {
				p = positions.get(i);
//				if (b.isIsolatingMove(x, y, p[0], p[1]))
//					hasIsoMove = true;
				int count = b.getWallCount(p[0], p[1]);
				if (b.isArticulationPoint(p[0], p[1]))
					count -= 4;
				if (count == 4) //it's a trap!
					count -= 10;
				if (!wallCounts.isEmpty()) {
					int j = 0;
					while (wallCounts.size() > j && wallCounts.get(j)[0] > count)
						j++;
					wallCounts.add(j, new int[] {count, i, -1});
				}
				else {
					wallCounts.add(new int[] {count, i, -1});
				}
			}
			
//			if (hasIsoMove) {
//				newList.clear();
//				for (int i = 0; i < wallCounts.size(); i++) {
//					//get the space
//					int[] wall = wallCounts.get(i);
//					int ind = wall[1];
//					p = positions.get(ind);
//					int space = b.getFreeSpace(x, y, p[0], p[1]);
//					wall[2] = space;
//					
//					if (!newList.isEmpty()) {
//						int j = 0;
//						while (newList.size() > j && newList.get(j)[2] > space)
//							j++;
//						newList.add(j, wall);
//					}
//					else {
//						newList.add(wall);
//					}
//				}
//				int bestIndex = newList.get(0)[1];
//				return moves.get(bestIndex);
//			}

			int bestIndex = wallCounts.get(0)[1];
			return moves.get(bestIndex);
		}
	}
	
}
